//
//  PhotoTestViewcontroller.swift
//  YCCamera
//
//  Created by Billy on 2024/5/16.
//

import UIKit
import Photos
import Vision

class PhotoTestViewcontroller: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    let screenWidth = UIScreen.main.bounds.size.width
    let screenHeight = UIScreen.main.bounds.size.height
    let collectionMaxCount: CGFloat = 4.0
    
    var isScan = false
    
    var collectionView: UICollectionView!
    
    var dataArray: [(month: String, photos: [(asset: PHAsset, feature: VNFeaturePrintObservation?)])] = []
    
    public lazy var item: UIBarButtonItem = {
        let btn = UIBarButtonItem(title: "开始扫描", style: .plain, target: self, action: #selector(rightBtnClick))
        btn.tintColor = .black
        return btn
    }()
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        createCollectionView()
    }
    
    func setupUI () {
        self.title = "图片相似度"
        self.view.backgroundColor = .white
                
        // 将按钮添加到导航栏右上角
        self.navigationItem.rightBarButtonItem = self.item
    }
    
    func createCollectionView() {
        // 创建一个UICollectionViewFlowLayout实例
        let layout = UICollectionViewFlowLayout()
        
        let width = min(screenWidth, screenHeight)
        
        let columnCount = collectionMaxCount
        
        let itemW = (width - 1.5 * columnCount) / columnCount
        let itemH = (width - 1.5 * columnCount) / columnCount
        
        layout.itemSize = CGSize(width: itemW, height: itemH)
        layout.minimumInteritemSpacing = 1.5
        layout.minimumLineSpacing = 1.5
        layout.sectionInset = UIEdgeInsets(top: 3, left: 0, bottom: 3, right: 0)
        layout.headerReferenceSize = CGSizeMake(screenWidth, 20)
        layout.sectionHeadersPinToVisibleBounds = true
        
        // 创建UICollectionView实例
        collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        
        // 注册UICollectionViewCell类
        collectionView.register(YCCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        
        // 设置数据源和代理
        collectionView.dataSource = self
        collectionView.delegate = self
        
        // 将UICollectionView添加到视图控制器的视图中
        self.view.addSubview(collectionView)
    }
    //开始扫描
    @objc func rightBtnClick(button: UIButton) {
        
        if !self.isScan {
            self.isScan = true
            
//            loadImageData()
            
            // 获取每个月的照片合集并更新UI
            YCPhotoTestManager.fetchMonthlyPhotoCollections { [weak self] monthlyPhotoCollections in
                self?.dataArray = monthlyPhotoCollections
                self?.collectionView.reloadData()
            }
        }
    }
    
    func loadImageData() {
        
        
        AMPhotoManager.fetchSimilarArray { dataArray in
//            self.dataArray = dataArray
            
            // 计算相似总数
//            var count = 0
//            for array in self.dataArray {
//                count += array.count
//            }
//            
//            // 加载完毕刷新数据
//            DispatchQueue.main.async {
//                self.isScan = false
//                self.collectionView.reloadData()
//                let title = "相似图片\(count)张"
//                self.title = title
//            }
        }
        
    }
    
    func loadImageForMonth() {
        
    }
    
    // 返回节中的项目数
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let sectionArray = self.dataArray[section]
        print("...item个数为\(sectionArray.photos.count)")
        return sectionArray.photos.count
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.dataArray.count
    }
    
    // 返回cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let sectionArray = self.dataArray[indexPath.section]
        let asset = sectionArray.photos[indexPath.item].asset
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! YCCollectionViewCell
        configureCell(cell, with: asset)
        
        return cell
    }
    
    func configureCell(_ cell: YCCollectionViewCell, with asset: PHAsset) {
        // 获取照片的缩略图并显示在cell中
        let imageManager = PHImageManager.default()
        let options = PHImageRequestOptions()
        options.deliveryMode = .highQualityFormat
        options.isSynchronous = false
        
        imageManager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill, options: options) { image, _ in
            cell.imageView.image = image
        }
    }
}

